<?php

namespace ulit\thirdPayment;

use think\response\Json;
use ulit\Base;

class SafePay
{

    private static SafePay $instance;
    private string $appkey='jo_pay_0esLlpae0kdqR39eFXBlY5TOq';
    private string $apiSecret='961a8e84f60b2676c12ec4a8039ab176';
    private string $baseUrl = 'https://pay.new.jieoukeji.cn/jo-pay-open-api';

    private string $appConfigId='8529364103645593601';
    private function __construct()
    {
        // 可以在这里初始化一些资源或配置
    }

    // 私有克隆方法，防止外部克隆
    private function __clone()
    {
    }

    // 获取类的实例
    public static function getInstance(): SafePay
    {
        if (!isset(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }
    private string $apiVersion='/v1/safe/';

    // 私有构造函数，防止外部实例化
    /**
     * 获取毫秒
     * @return int
     */
    public function getMillisecond(): int
    {
        $time = explode (" ", microtime () );
        $time = $time [1] . ($time [0] * 1000);
        $time2 = explode ( ".", $time );
        return $time2 [0];
    }

    /**
     * 公共请求接口
     * @param $url
     * @param $postData
     * @param string $method
     * @return bool|string|Json
     */
    public  function curlPay($url, $postData, string $method="POST"): Json|bool|string
    {
        $url = $this->baseUrl.$url;
        $apiKey = $this->appkey;
        $apiSecret = $this->apiSecret;
        $clientType = '1';
        $clientVersion = '1.0.0';
        $access_timestamp = $this->getMillisecond();
        //签名规则md5
        //open_api_vf12kwQ75v7xd333${clientType}${clientVersion}${apiKey}${apiSecret}${timestamp}
        $access_sign = md5("pay_open_api_pVvXnfs1bSZbz".$clientType.$clientVersion.$apiKey.$apiSecret.$access_timestamp);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => [
                "access-sign: ".$access_sign,
                "access-timestamp: ".$access_timestamp,
                "api-key: ".$apiKey,
                "api-secret: ".$apiSecret,
                "client-type: ".$clientType,
                "client-version: ".$clientVersion,
                "content-type: application/json" //json
            ],
        ]);
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $response;
    }


    /***
     * @title  --打款到支付宝，银行卡
     * @param string $orderCode --打款订单号，最大32位长度字符串，不重复
     * @param string $cardNo  --支付宝账户或银行卡卡号
     * @param string $name  --姓名
     * @param string $withdrawType  --提现类型：1银行卡，2支付宝
     * @param string $remark  --备注
     * @param double $money  --打款金额（两位小数，示例：110.23）
     * @param string $appConfigId  --应用（通道）配置ID，两种获取方式：1.登录管理后台，个人中心->应用管理：应用卡片右上角复制；2.调用接口:1.
     * @param string|null $accountType  --提现到银行卡时，账户类型：00对私，01对公，默认：00对私
     * @param string|null $bankName   --提现到银行卡时，开户行名称，对公必传，填写银行名称，不需要具体的支行
     * @param string|null $brachBankCode  --提现到银行卡时，开户行联行号，对公必传
     * @return bool|string|Json
     */

    public function withdraw(string $orderCode, string $cardNo, string $name, string $withdrawType, string $remark, float $money, string $appConfigId, string $accountType=null, string $bankName=null, string $brachBankCode=null): Json|bool|string
    {

        $url=$this->apiVersion."withdraw";
        $data=[
            'orderCode'=>$orderCode,
            'cardNo'=>$cardNo,
            'name'=>$name,
            'withdrawType'=>$withdrawType,
            'remark'=>$remark,
            'money'=>amountFormat($money),
            'appConfigId'=>$this->appConfigId
        ];

        $accountType && $data['accountType']=$accountType;
        $brachBankCode && $data['brachBankCode']=$brachBankCode;
        $bankName && $data['bankName']=$bankName;

        return $this->curlPay($url,json_encode($data,JSON_UNESCAPED_UNICODE));
    }


    /***
     * @查询订单查询打款状态
     * 【必选】打款不会立即返回状态，通过查询或回调方式获取打款状态，查询接口我们建议是必须接入，回调作为辅助
     * 建议：打款后每隔3秒查询一次处理中（订单状态值为2）的订单，订单状态不为2终止查询操作。
     * *银行卡到账不保证时效，有时候1-2个小时属于正常情况**
     *
     * @param string $orderCode 打款时传入的订单号
     * @return Json|bool|string
     */
    public function query(string $orderCode): Json|bool|string
    {
        $url=$this->apiVersion."query?orderCode=".$orderCode;
        return $this->curlPay($url,'','GET');
    }






}